package demo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-20
 * Time: 22:52
 */
public class Demo2 {
    /**
     * 生产者消费者模型： 至少生产者一个线程, 消费者一个线程.
     * @param args
     */
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new LinkedBlockingDeque<>();

        Thread producer = new Thread(()->{
            int n = 0;
            while (true){
                try {
                    queue.put(n);
                    System.out.println("生产元素 " + n);
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                n++;
            }
        },"producer ");


        Thread consumer = new Thread(()->{

            while (true){
                try {
                    Integer n = queue.take();
                    System.out.println("消费元素 " + n);
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"consumer ");


        producer.start();
        consumer.start();
    }
}
